package com.ruoyi.costQuery.http;

import com.google.gson.Gson;
import com.ruoyi.costQuery.domain.AccessVO;
import com.ruoyi.file.PropertiesUtils;
import com.ruoyi.json.JSONArray;
import com.ruoyi.json.JSONObject;
import com.ruoyi.json.JsonTools;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import sun.misc.BASE64Decoder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class HttpMethodUtil {
    private static Log logger = LogFactory.getLog(HttpMethodUtil.class);

    public static String doJsonPost(String urlPath, String json) { // 物业调用房产
        // HttpClient 6.0被抛弃了
        String result = "";
        BufferedReader reader = null;
        try {
            URL url = new URL(urlPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            // 设置文件类型:
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            // 设置接收类型否则返回415错误
            // conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
            conn.setRequestProperty("accept", "application/json");
            // 往服务器里面发送数据
            if (json != null) {
                byte[] writebytes = json.getBytes();
                // 设置文件长度
                conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream outwritestream = conn.getOutputStream();
                outwritestream.write(json.getBytes());
                outwritestream.flush();
                outwritestream.close();
            }
            if (conn.getResponseCode() == 200) {
//                reader = new BufferedReader(
//                        new InputStreamReader(conn.getInputStream()));
//                result = reader.readLine();
                StringBuilder stringBuilder = new StringBuilder();
                getResponseTextV2(conn.getInputStream(), stringBuilder);
                result = stringBuilder.toString();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (reader != null) {
                try {
                    reader.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    private static void getResponseTextV2(InputStream netIps, StringBuilder builder) throws Exception {
        byte[] buffer = new byte[1024];
        int len;
        while ((len = netIps.read(buffer)) != -1) {
            builder.append(new String(buffer, 0, len, "UTF-8"));
        }

    }

    public static Map<String,String> getMessage(String url, Object data) {
        UUID uuid = UUID.randomUUID();
        String uuidStr = uuid.toString().replace("-", "").substring(0, 18);
        AccessVO access = new AccessVO();
        JsonTools jsonTools = new JsonTools();
        Gson gson = new Gson();
        String message = "";
        access.setAppid("CSWYWXZJGLZXV4994321");
        access.setRegion("220000");
        access.setDeptcode("008101");
        access.setVersion("1.0");
        access.setNoise(uuidStr);
        String json1 = gson.toJson(data);
        logger.info("data：" + json1);
        json1 = Base64.encodeBase64String(json1.getBytes(Charset.forName("UTF-8")));
        access.setData(json1);
        String stringA = "region=" + access.getRegion() + "&deptcode=" + access.getDeptcode() + "&appid="
                + access.getAppid() + "&data=" + access.getData() + "&noise=" + access.getNoise();
        String stringSignTemp = stringA + "&key=09614812596986675146328568&version=1.0";
        String sign = DigestUtils.md5Hex(stringSignTemp.toString().getBytes(Charset.forName("UTF-8"))).toUpperCase();
        access.setSign(sign);
        String json2 = gson.toJson(access);
        Httpclient hc = new Httpclient();
        logger.info("请求报文：" + json2);

        String ss = HttpMethodUtil.doJsonPost("http://"+hc.getHttpClientIp()+":"+hc.getHttpClientPort()
        +hc.getClientUrl()+url,json2);
        logger.info("响应报文：" + ss);
        Map<String,String> map = new HashMap<String,String>();
        try {
            JSONArray jsonArray1 = jsonTools.stringToJsonArray(ss);
            JSONObject jsonObject1 = jsonArray1.getJSONObject(0);
            BASE64Decoder decoder = new BASE64Decoder();
            String data1 = new String(Base64.decodeBase64(String.valueOf(jsonObject1.get("data"))), "UTF-8");
            logger.info("data1：" + data1);
            JSONArray jsonArray2 = jsonTools.stringToJsonArray(data1);
            JSONObject jsonObject2 = jsonArray2.getJSONObject(0);
            map.put("result", String.valueOf(jsonObject2.get("result")));
            map.put("message", new String(Base64.decodeBase64(String.valueOf(jsonObject2.get("message"))), "UTF-8"));
            logger.info("data2：" + new String(Base64.decodeBase64(String.valueOf(jsonObject2.get("message"))), "UTF-8"));
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return map;
    }

}
